/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月27日
 */
package com.massyframework.beanskin.protocol.module;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleNotFoundException;
import com.massyframework.beanskin.SimpleModuleIdentifier;
import com.massyframework.beanskin.fragment.Fragment;
import com.massyframework.beanskin.framework.Framework;
import com.massyframework.beanskin.util.FrameworkUtils;
import com.massyframework.beanskin.util.classloading.ModuleClassLoader;
import com.massyframework.beanskin.util.version.Version;

/**
 * 基于classpath的URL流处理器
 * @author huangkh
 *
 */
public class Handler extends URLStreamHandler {

	/**
	 * 
	 */
	public Handler() {
	}

	@Override
	protected URLConnection openConnection(URL url) throws IOException {
		Framework framework = FrameworkUtils.getInstance();
		if (framework == null) 
			throw new IOException("framework is not running.");
		String[] arr = url.getPath().split("/");
		if (arr.length < 4) {
			throw new IOException("invalid path: " + url.getPath());
		}
		
		ModuleIdentifier identifier =SimpleModuleIdentifier.newBuilder()
				.groupId(arr[0])
				.moduleId(arr[1])
				.version(Version.valueOf(arr[2]))
				.build();
		Module<?> module = framework.findModuleByIdentifier(identifier);
		if (module == null) {
			throw new ModuleNotFoundException(identifier);
		}
		
		int length = arr[0].length() + arr[1].length() + arr[2].length() + 3;
		String name = url.getPath().substring(length);

		ModuleClassLoader classLoader = module.getModuleClassLoader();
		URL innerUrl = classLoader.getResource(name);
		URLConnection result = innerUrl.openConnection();
		if (module instanceof Fragment) {
			//fragment支持热拔插，所以不能使用缓存
			result.setUseCaches(false);
		}
		
		return result;
	}

}
